using Newtonsoft.Json;

namespace Dan.Common.Extend
{
    public static class JsonExtend
    {
        /// <summary>
        /// To the json.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="isthrowexception">if set to <c>true</c> [isthrowexception].</param>
        /// <returns></returns>
        public static string Serialize(this object obj, bool isthrowexception = true)
        {
            try
            {
                var str = obj.SafeToString();
                if (string.IsNullOrEmpty(str))
                    return str;
                return JsonConvert.SerializeObject(obj);
            }
            catch
            {
                if (isthrowexception)
                {
                    throw;
                }
                return string.Empty;
            }
        }


        /// <summary>
        /// Deserializes the specified isthrowexception.
        /// </summary>
        /// <param name="str">The string.</param>
        /// <param name="isthrowexception">if set to <c>true</c> [isthrowexception].</param>
        /// <returns></returns>
        public static T Deserialize<T>(this string str, bool isthrowexception = true)
        {
            try
            {
                if (string.IsNullOrEmpty(str))
                    return default(T);
                return JsonConvert.DeserializeObject<T>(str);
            }
            catch
            {
                if (isthrowexception)
                {
                    throw;
                }
                return default(T);
            }
        }
    }
}